import { defineStore } from "pinia";
import axios from "axios";

export const useMainStore = defineStore("main", {
  state: () => {
    return { _user: null };
  },
  getters: {
    user(state) {
      return state._user || JSON.parse(sessionStorage.getItem("UserInfo"));
    },
  },
  actions: {
    login(obj) {
      return new Promise((resolve, reject) => {
        axios
          .post("/account/login", obj)
          .then((res) => {
            const { success, data, msg } = res;
            if (success) {
              sessionStorage.setItem("Authorization", data.token);
              sessionStorage.setItem("UserInfo", JSON.stringify(data.user));
              this._user = data.user;
              resolve();
            } else {
              reject(msg);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    loginOut() {
      sessionStorage.removeItem("UserInfo");
      sessionStorage.removeItem("Authorization");
      this._user = null;
    },
  },
});
